﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;

namespace huangyufan.OpenDataService.Middleware
{
    public class CheckRequestMiddleware
    {
        private readonly RequestDelegate _next;

        public CheckRequestMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Method != "GET")
            {
                context.Response.StatusCode = 400;
                return;
            }
            string[] pathRoute = context.Request.Path.Value.Split('/', StringSplitOptions.RemoveEmptyEntries);///api/opendata/test
            if (pathRoute.Length < 3)
            {
                context.Response.StatusCode = 400;
                return;
            }
            context.Request.Path =new PathString($"/{pathRoute[2]}");
            await _next(context);
        }
    }

    public static class CheckRequestMiddlewareExtensions
    {
        public static IApplicationBuilder UseCheckRequestMiddleware(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CheckRequestMiddleware>();
        }
    }
}
